import Vue from "vue";
import VueRouter from "vue-router";
import login from "@/views/user/login.vue";
import home from "@/views/home/home.vue";
import movie from "@/views/movie/movie.vue";
import qa from "@/views/qa/qa.vue";
import user from "@/views/user/user.vue";
import notfound from "@/views/notfound/notfound.vue";
import edit from "@/views/user/edit.vue";
import student from "@/views/user/student.vue";
import details from "@/views/home/details.vue";
import search from "@/views/home/search.vue";
import searchResults from "@/views/home/searchResults.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/login",
    name: "login",
    component: login
  },
  {
    path: "/home",
    name: "home",
    component: home,
    // 路由元信息作用：给路由中单个组件添加数据，实现一些特定业务逻辑。如元素显示/隐藏等
    // 路由元信息
    meta: { showTab: true }
  },
  {
    path: "/movie",
    name: "movie",
    component: movie,
    meta: { showTab: true }
  },
  {
    path: "/qa",
    name: "qa",
    component: qa,
    meta: { showTab: true }
  },
  {
    path: "/user",
    name: "user",
    component: user,
    meta: { showTab: true, isLogin: true }
  },
  {
    path: "/notfound",
    name: "notfound",
    component: notfound
  },
  {
    path: "/edit",
    name: "edit",
    component: edit
  },
  {
    path: "/student",
    name: "student",
    component: student
  },
  {
    path: "/details",
    name: "details",
    component: details
  },
  {
    path: "/search",
    name: "search",
    component: search
  },
  {
    path: "/searchResults",
    name: "searchResults",
    component: searchResults
  },
  // 路由重定向
  {
    path: "/",
    redirect: "/home"
  },
  {
    path: "*",
    redirect: "/notfound"
  }
];
const originPush = VueRouter.prototype.push;
//(2)替换原型链中的push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    // 正常执行
    //originalPush.call() : 我们自定义的push底层还是调用默认的push
    return originPush.call(this, location, onResolve, onReject);
  }
  //如果有异常，本来这个err默认是抛出的，我们直接不做任何处理（给吞掉了）
  /* 
  底层默认是抛出异常：err => {throw err}
  我们不抛出，不做任何处理：err => err
  */
  return originPush.call(this, location).catch(err => {});
};

const router = new VueRouter({
  routes
});

// 导入token
import { getToken } from "@/utils/token.js";
// 注册导航守卫 (全局前置守卫  跳转之前执行)
router.beforeEach((to, from, next) => {
  // console.log(getToken)

  //判断用户没有没有登录

  // next()不传参就是正常跳转 传参 跳转到你指定的页面去
  // 这里取反getToken 的意思是 只有你没有登录（token 为空）这个式子才成立
  if (to.meta.isLogin && !getToken()) {
    //没有登录，则跳转登录页
    next({ path: "/login" });
  } else {
    //有登录，正常跳转
    next();
  }
});
export default router;
